/**
 * 
 * request 封装 
 */

const request = (url, options, token) => {
  const baseUrl = 'https://www.bisaiquan.cn/api/'
  wx.showLoading({
    title: '加载中...',
    mask: true
  })

  return new Promise((resolve, reject) => {
    wx.request({
      url: `${baseUrl}${url}`,
      method: options.method,
      data: options.method === 'GET' ? options.data : JSON.stringify(options.data),
      header: {
        'Content-Type': 'application/json; charset=UTF-8',
        'open_token': token
      },
      success(res) {
        wx.hideLoading()
        if (res.statusCode !== 200) {
          reject(res.data)
          wx.showToast({
            title: res.errMsg,
            icon: 'none',
            duration: 2000,
            mask: true
          })
        } else {
          resolve(res.data)
        }
      },
      fail(error) {
        wx.hideLoading()
        reject(error.data)
      },
      complete() {
        wx.hideLoading()
      }
    })
  })
}

//封装get方法
const get = (url, options = {}) => {
  return request(url, {
    method: 'GET',
    data: options
  })
}

//封装post方法
const post = (url, options = {}) => {
  let token = wx.getStorageSync('openToken')
  return request(url, {
    method: 'POST',
    data: options
  }, token)
}

//封装put方法
const put = (url, options) => {
  return request(url, {
    method: 'PUT',
    data: options
  })
}
//封装remove方法，DELETE关键字不能声明
const remove = (url, options = {}) => {
  return request(url, {
    method: 'DELETE',
    data: options
  })
}

module.exports = {
  get,
  post,
  put,
  remove
}